import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:base_flutter/base_flutter.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'page/login/login_page.dart';
import 'services/api_service.dart';
import 'utils/logger.dart';

// 创建一个全局的导航键
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

void main() async {
  // 记录启动时间
  final startTime = DateTime.now();
  Logger.d('APP_STARTUP', 'App started at: $startTime');
  
  // 确保Flutter引擎初始化
  WidgetsFlutterBinding.ensureInitialized();
  Logger.d('APP_STARTUP', 'WidgetsFlutterBinding initialized');
  
  // 针对Android 15的兼容性配置
  if (defaultTargetPlatform == TargetPlatform.android) {
    Logger.d('APP_STARTUP', 'Running on Android platform');
    
    // 限制图像缓存大小以解决Android 15上的内存问题
    PaintingBinding.instance.imageCache.maximumSizeBytes = 1024 * 1024 * 10; // 10MB
    Logger.d('APP_STARTUP', 'Image cache size limited to 10MB');
    
    // 确保在Android上使用合适的渲染设置
    Logger.d('APP_STARTUP', 'Applying Android-specific rendering optimizations');
  }
  
  // 初始化SharedPreferences，确保在Android 15上正常工作
  try {
    final prefs = await SharedPreferences.getInstance();
    Logger.d('APP_STARTUP', 'SharedPreferences initialized successfully at: ${DateTime.now().difference(startTime).inMilliseconds}ms');
    
    // 初始化ApiService以恢复token
    await ApiService().initialize();
    Logger.d('APP_STARTUP', 'ApiService initialized at: ${DateTime.now().difference(startTime).inMilliseconds}ms');
  } catch (e) {
    Logger.e('APP_STARTUP', 'Failed to initialize SharedPreferences', exception: e as Exception);
    // 即使SharedPreferences初始化失败，也继续启动应用
  }
  
  // 检查网络连接状态
  try {
    final connectivityResult = await Connectivity().checkConnectivity();
    Logger.d('APP_STARTUP', 'Network connectivity: $connectivityResult');
  } catch (e) {
    Logger.e('APP_STARTUP', 'Failed to check network connectivity', exception: e as Exception);
  }
  
  Logger.d('APP_STARTUP', 'Starting app at: ${DateTime.now().difference(startTime).inMilliseconds}ms');
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _isInitialized = false;
  final startTime = DateTime.now();

  @override
  void initState() {
    super.initState();
    Logger.d('APP_INIT', 'MyAppState initState started at: ${DateTime.now().difference(startTime).inMilliseconds}ms');
    _initializeApp();
  }

  Future<void> _initializeApp() async {
    Logger.d('APP_INIT', 'App initialization started at: ${DateTime.now().difference(startTime).inMilliseconds}ms');
    
    try {
      // 为Android 15添加特定的平台检测
      if (defaultTargetPlatform == TargetPlatform.android) {
        // 在Android上使用WidgetsBinding确保UI线程安全
        WidgetsBinding.instance.addPostFrameCallback((_) async {
          await _initializeNetworkManager();
        });
      } else {
        // 在其他平台直接初始化
        await _initializeNetworkManager();
      }
    } catch (e) {
      Logger.e('APP_INIT', 'Critical initialization error at: ${DateTime.now().difference(startTime).inMilliseconds}ms', exception: e as Exception);
      // 即使发生严重错误，也确保应用能够继续启动
      _forceInitializeApp();
    }
  }

  Future<void> _initializeNetworkManager() async {
    try {
      // 先显示启动画面，然后延迟初始化网络
      Logger.d('APP_INIT', 'Waiting for splash screen display at: ${DateTime.now().difference(startTime).inMilliseconds}ms');
      await Future.delayed(const Duration(milliseconds: 500)); // 减少延迟时间
      
      // 异步初始化NetworkManager，但不阻塞UI
      Logger.d('APP_INIT', 'Starting NetworkManager initialization at: ${DateTime.now().difference(startTime).inMilliseconds}ms');
      
      // 在单独的future中初始化网络，不阻塞UI线程
      final networkFuture = Future(() async {
        try {
          NetworkManager().init(
            'http://192.168.1.201:8080', // 使用正确的开发服务器地址
            config: NetworkConfig(
              connectTimeout: const Duration(seconds: 15),
              receiveTimeout: const Duration(seconds: 15),
              sendTimeout: const Duration(seconds: 15),
            ),
          );
          Logger.d('APP_INIT', 'NetworkManager initialized successfully at: ${DateTime.now().difference(startTime).inMilliseconds}ms');
        } catch (e) {
          Logger.e('APP_INIT', 'NetworkManager initialization error', exception: e as Exception);
        }
      });
      
      // 不等待网络初始化完成，直接标记应用为已初始化，避免卡住UI
      _markAppAsInitialized();
      
      // 但仍尝试完成网络初始化（在后台）
      await networkFuture.catchError((e) {
        Logger.w('APP_INIT', 'Network initialization failed but app continues: $e');
      });
    } catch (e) {
      Logger.e('APP_INIT', 'Network initialization process error', exception: e as Exception);
      _forceInitializeApp();
    }
  }

  void _markAppAsInitialized() {
    if (mounted) {
      setState(() {
        _isInitialized = true;
        Logger.d('APP_INIT', 'App marked as initialized at: ${DateTime.now().difference(startTime).inMilliseconds}ms');
      });
    } else {
      Logger.w('APP_INIT', 'Context not mounted when trying to mark app as initialized');
    }
  }

  void _forceInitializeApp() {
    // 强制标记应用为已初始化，无论发生什么错误
    Logger.w('APP_INIT', 'Forcing app initialization at: ${DateTime.now().difference(startTime).inMilliseconds}ms');
    if (mounted) {
      setState(() {
        _isInitialized = true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: navigatorKey, // 设置全局导航键
      title: 'Matrix - 价值交友平台',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        primaryColor: const Color(0xFF2196F3),
        colorScheme: ColorScheme.fromSeed(
          seedColor: const Color(0xFF2196F3),
          brightness: Brightness.light,
        ),
        visualDensity: VisualDensity.adaptivePlatformDensity,
        appBarTheme: const AppBarTheme(
          backgroundColor: Color(0xFF2196F3),
          foregroundColor: Colors.white,
          elevation: 0,
        ),
        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ElevatedButton.styleFrom(
            backgroundColor: const Color(0xFF2196F3),
            foregroundColor: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
          ),
        ),
        // 添加字体配置以解决在微信小程序环境中的字体加载问题
        fontFamily: 'sans-serif',
        textTheme: const TextTheme(
          bodyLarge: TextStyle(fontFamily: 'sans-serif'),
          bodyMedium: TextStyle(fontFamily: 'sans-serif'),
          bodySmall: TextStyle(fontFamily: 'sans-serif'),
          headlineLarge: TextStyle(fontFamily: 'sans-serif'),
          headlineMedium: TextStyle(fontFamily: 'sans-serif'),
          headlineSmall: TextStyle(fontFamily: 'sans-serif'),
          titleLarge: TextStyle(fontFamily: 'sans-serif'),
          titleMedium: TextStyle(fontFamily: 'sans-serif'),
          titleSmall: TextStyle(fontFamily: 'sans-serif'),
        ),
      ),
      home: _isInitialized ? const LoginPage() : const SplashScreen(),
      // 禁用字体缓存以避免在微信小程序环境中的字体加载问题
      builder: (context, child) {
        return MediaQuery(
          data: MediaQuery.of(context).copyWith(
            // 强制使用默认字体渲染
            boldText: false,
          ),
          child: child ?? Container(),
        );
      },
    );
  }
}

class SplashScreen extends StatelessWidget {
  const SplashScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF2196F3),
      body: const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.person,
              size: 80,
              color: Colors.white,
            ),
            SizedBox(height: 20),
            Text(
              'Matrix',
              style: TextStyle(
                fontSize: 32,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            SizedBox(height: 10),
            Text(
              '价值交友平台',
              style: TextStyle(
                fontSize: 16,
                color: Colors.white70,
              ),
            ),
            SizedBox(height: 40),
            CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
            ),
          ],
        ),
      ),
    );
  }
}
